package com.bwie.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.injector.methods.SelectById;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bwie.mapper.ImgsMapper;
import com.bwie.mapper.MaintainMapper;
import com.bwie.pojo.Imgs;
import com.bwie.pojo.Maintain;
import com.bwie.pojo.RepairDateVo;
import com.bwie.utils.R;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import io.jsonwebtoken.Jwts;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Select;
import org.checkerframework.checker.units.qual.A;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.mapper.RepaisMapper;
import com.bwie.pojo.Repais;
import com.bwie.service.RepaisService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

@Service
@Transactional(rollbackFor = Exception.class)
public class RepaisServiceImpl extends ServiceImpl<RepaisMapper, Repais> implements RepaisService{

    @Autowired
    private RepaisMapper repaisMapper;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private FastFileStorageClient storageClient;

    @Autowired
    private ImgsMapper imgsMapper;

    @Autowired
    private MaintainMapper maintainMapper;


    @Override
    public R getWeekCount() {
        List<RepairDateVo> list = repaisMapper.getWeekCount();

        List<String> x = new ArrayList<>();
        List<Integer> y = new ArrayList<>();
        for (RepairDateVo repairDateVo : list) {
            x.add(repairDateVo.getX());
            y.add(repairDateVo.getY());
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("x",x);
        map.put("y",y);

        return R.OK(map);
    }

    @Override
    public R getYearMonthCount() {

        List<String> x = repaisMapper.getYear();

        List<Integer> y1 = repaisMapper.getMonthDate(0);
        List<Integer> y2 = repaisMapper.getMonthDate(1);
        List<Integer> y3 = repaisMapper.getMonthDate(2);
        List<Integer> y4 = repaisMapper.getMonthDate(3);

        HashMap<String, Object> map = new HashMap<>();
        map.put("x",x);
        map.put("y1",y1);
        map.put("y2",y2);
        map.put("y3",y3);
        map.put("y4",y4);


        return R.OK(map);
    }

    @Override
    public R getRegionStatusCount() {
        //获取 x 的数据
        List<String> x = repaisMapper.getRegion();
        //获取 y 的数据
        List<Integer> y1 = repaisMapper.getStatusCount(0);
        List<Integer> y2 = repaisMapper.getStatusCount(1);
        List<Integer> y3 = repaisMapper.getStatusCount(2);
        List<Integer> y4 = repaisMapper.getStatusCount(3);

        HashMap<String, Object> map = new HashMap<>();
        map.put("x",x);
        map.put("y1",y1);
        map.put("y2",y2);
        map.put("y3",y3);
        map.put("y4",y4);


        return R.OK(map);
    }

    @Override
    public R getRepairList(Repais repais) {

        Page<Repais> page = new Page<>(repais.getCurrentPage(), repais.getPageSize());

        Page<Repais> repairsList = repaisMapper.getRepairList(page,repais);

        for (Repais img : repairsList.getRecords()) {
            List<Imgs> imgsList = imgsMapper.selectList(
                    new QueryWrapper<Imgs>().lambda().eq(Imgs::getRepairId,img.getRepaisId())
            );
            img.setImgs(imgsList);
        }

        return R.OK(repairsList);
    }

    @Override
    public R addRepairs(Repais repais) {

        //提交校验
        if (StringUtils.isEmpty(repais.getFacilityName())){
            return R.ERROR(500,"报修设备不能为空");
        }
        if(repais.getRepaisArea()==null){
            return R.ERROR(500,"请选择报修区域");
        }
        if (repais.getCategoryId()==null){
            return R.ERROR(500,"请选择设备类目");
        }
        if (StringUtils.isEmpty(repais.getRepaisContent())){
            return R.ERROR(500,"设备损坏原因请填写");
        }

        //添加报修单
        String repairCode = DateUtil.format(new Date(),"yyyyMMdd")+RandomUtil.randomNumbers(6);
        String token = request.getHeader("token");
        Integer userId = Jwts.parser().setSigningKey("bwie").parseClaimsJws(token).getBody().get("userId", Integer.class);
        repais.setRepaisCode(repairCode);
        repais.setUserId(userId);
        repais.setRepaisTime(new Date());
        repais.setRepaisStatus(0);
        int i = repaisMapper.insert(repais);

        for (Imgs img : repais.getImgs()) {
            img.setRepairId(repais.getRepaisId());
            imgsMapper.insert(img);
        }

        Maintain maintain = new Maintain();
        maintain.setRepaisId(repais.getRepaisId());
        maintain.setRepaisStatus(0);
        maintain.setUserId(userId);
        maintain.setCreateTime(new Date());

        maintainMapper.insert(maintain);


        return i>0?R.OK("添加成功"):R.ERROR(500,"添加失败");
    }

    @Override
    public R upLoadFile(MultipartFile file) {
        try {
            //获取文件的拓展名
            String extName = FileUtil.extName(file.getOriginalFilename());
            //上传文件到FastDFS,返回存储路径
            StorePath storePath = storageClient.uploadFile(
                    file.getInputStream(), // 文件输入流
                    file.getSize(),  // 文件大小
                    extName, //文件名称
                    null //元数据（可选 , null）
            );
            //拼接完整的文件访问URL
            String path = "http://192.168.80.192:8888/"+storePath.getFullPath();
            return R.OK(path);
        } catch (IOException e) {
            e.printStackTrace();
            return R.ERROR(500,"文件上传失败");
        }
    }

    @Override
    public R updateRepair(Repais repais) {
        int i = repaisMapper.updateById(repais);
        return i>0?R.OK("修改成功"):R.ERROR(500,"修改失败");
    }

    @Override
    public R AcceptedUpdate(Repais repais) {
        int i = repaisMapper.updateById(repais);

        Maintain maintain = new Maintain();
        maintain.setRepaisId(repais.getRepaisId());
        maintain.setRepaisStatus(repais.getRepaisStatus());
        maintain.setCreateTime(new Date());
        maintain.setUserId(repais.getUserId());
        maintain.setRepairUserId(repais.getRepaisUserId());

        maintainMapper.insert(maintain);

        return i>0 ? R.OK("处理完成"):R.ERROR(500,"处理失败");
    }

    @Override
    public R TransferUpdate(Repais repais) {
        repais.setRepaisStatus(3);
        int i = repaisMapper.updateById(repais);

//        //4.入库单号,系统自动生成[规则:yyyyMMddHHmmSS+4位随机数]
//        String hmmSS = DateUtil.format(new Date(), "yyyyMMddHHmmSS") + RandomUtil.randomNumbers(4);

        Maintain maintain = new Maintain();
        maintain.setRepaisId(repais.getRepaisId());
        maintain.setRepaisStatus(repais.getRepaisStatus());
        maintain.setCreateTime(new Date());
        maintain.setUserId(repais.getUserId());
        maintain.setRepairUserId(repais.getRepaisUserId());
        maintain.setRemark(repais.getRemark());

        maintainMapper.insert(maintain);

        return i > 0?R.OK("转单成功"):R.ERROR(500,"转单失败");
    }
}
